<template>
  <Modal
    :mask-closable="false"
    v-model="deviceVisible"
    width="1200"
    :title="$t('fault.CreateAWorkOrder')"
    class="modal-content-layout other"
  >
    <!-- {{ formTop }} -->
    <Form
      ref="deviceForm"
      :model="formTop"
      label-position="top"
      :rules="validateDevice"
    >
      <div class="item">
        <Row :gutter="16">
          <Col :span="8">
            <FormItem label="工单号" prop="workCode">
              <Select
                v-model="formTop.workCode"
                filterable
                clearable
                placeholder="请输入工单号"
                :remote-method="handleRemote"
                :loading="searchLoading"
                @on-select="handleChange"
              >
                <Option
                  v-for="(item, i) in workOrderList"
                  :value="item.workCode"
                  :label="item.workCode"
                  :key="i"
                >
                </Option>
              </Select>
            </FormItem>
          </Col>
          <Col :span="8">
            <FormItem label="班次时间" prop="shiftTime">
              <DatePicker
                style="width: 100%"
                @on-change="shiftTimeChange"
                :value="formTop.shiftTime"
                type="date"
                placeholder="请选择班次时间"
              ></DatePicker>
            </FormItem>
          </Col>
          <Col :span="8">
            <FormItem label="班次" prop="shiftId">
              <Select
                v-model="formTop.shiftId"
                placeholder="请选择班次"
                @on-select="shiftChange"
              >
                <Option
                  v-for="(item, i) in shiftList"
                  :value="item.id"
                  :label="item.shift"
                  :key="i"
                >
                </Option>
              </Select>
            </FormItem>
          </Col>
        </Row>
        <Row :gutter="16">
          <Col :span="8">
            <FormItem label="投料类型" prop="feedingStatus">
              <Select v-model="formTop.feedingStatus" placeholder="请选择">
                <Option label="投料" value="投料"></Option>
                <Option label="退料" value="退料"></Option>
              </Select>
            </FormItem>
          </Col>
        </Row>
      </div>
      <!-- {{ social }} -->
      <CheckboxGroup v-model="social" v-if="addList.length > 0">
        <div class="mt16 item" v-for="(item, index) in addList" :key="index">
          <Checkbox :label="item">序号{{ index + 1 }}</Checkbox>
          <Row :gutter="16">
            <Col :span="8">
              <FormItem label="物料编号">
                <Input :value="item.materialCode" readonly />
              </FormItem>
            </Col>
            <Col :span="8">
              <FormItem label="物料名称" prop="materialName">
                <Input :value="item.materialName" readonly />
              </FormItem>
            </Col>
            <Col :span="8">
              <FormItem label="规格型号" prop="materialModel">
                <Input :value="item.materialModel" readonly />
              </FormItem>
            </Col>
          </Row>
          <Row :gutter="16">
            <Col :span="8">
              <FormItem label="材料牌号">
                <Input :value="item.materialMark" readonly />
              </FormItem>
            </Col>
            <Col :span="8">
              <FormItem label="额定用量" prop="quotaQuantity">
                <Input
                  :value="item.quotaQuantity ? item.quotaQuantity : 0"
                  readonly
                />
              </FormItem>
            </Col>
            <Col :span="8">
              <FormItem label="理论用量" prop="needQuantity">
                <Input
                  :value="item.needQuantity ? item.onDutyTotal : 0"
                  readonly
                />
              </FormItem>
            </Col>
          </Row>
          <Row :gutter="16">
            <Col :span="8">
              <FormItem label="物料批次">
                <Input v-model="item.materialBatch" />
              </FormItem>
            </Col>
            <Col :span="8">
              <FormItem label="材料牌号" prop="brand">
                <Input v-model="item.brand" />
              </FormItem>
            </Col>
            <Col :span="8">
              <FormItem label="数量" prop="weight" require>
                <InputNumber
                  :precision="3"
                  :active-change="false"
                  :step="1"
                  :max="9999999"
                  :parser="(val) => util.numberFormatNoFixed(val, 3)"
                  v-model="item.weight"
                />
              </FormItem>
            </Col>
          </Row>
          <Row :gutter="16">
            <Col :span="8">
              <FormItem label="单位" require>
                <Input v-model="item.unit" readonly />
              </FormItem>
            </Col>
            <Col :span="8">
              <FormItem label="出库仓库" prop="maintainApplyPhone" require>
                <Input :value="wareHouseList.backupName" readonly />
              </FormItem>
            </Col>
            <Col :span="8">
              <FormItem label="标签流水号" prop="tagSerialNumber">
                <Input v-model="item.tagSerialNumber" />
              </FormItem>
            </Col>
          </Row>
          <Row :gutter="16">
            <Col :span="8">
              <FormItem label="备注">
                <Input v-model="item.remarks" />
              </FormItem>
            </Col>
            <Col :span="8">
              <FormItem label="投退料仓库">
                <Select v-model="item.selectedWarehouseId" placeholder="请选择">
                  <Option v-for="(item,index) in wareHouseList2" :key="index" :label="item.backupName" :value="item.id"></Option>
               </Select>
              </FormItem>
            </Col>
          </Row>
        </div>
      </CheckboxGroup>
    </Form>
    <div slot="footer">
      <Button type="default" @click="deviceVisible = false">{{
        $t("common.Cancle")
      }}</Button>
      <Button type="primary" :loading="loadingVisible" @click="submit">{{
        $t("maintenance.Confirmed")
      }}</Button>
    </div>
    <commonModal ref="commonModal"></commonModal>

  </Modal>
</template>

<script>
import moment from "moment";
import commonModal from "@/components/modalTypes/commonModal.vue";

export default {
  name: "addModal",
  components: { commonModal},
  data() {
    return {
      social: [],
      deviceVisible: false,
      loadingVisible: false,
      searchLoading: false,
      formTop: {
        shiftTime: "",
      },
      shiftList: [],
      validateDevice: {
        workCode: [
          {
            required: true,
            message: `${this.$t("common.inputInfo")}`,
            trigger: "change",
          },
        ],
        shiftTime: [
          {
            required: true,
            message: `${this.$t("common.inputInfo")}`,
            trigger: "change",
          },
        ],
        shift: [
          {
            required: true,
            message: `${this.$t("common.inputInfo")}`,
            trigger: "change",
          },
        ],
        // weight: [
        //   {
        //     required: true,
        //     message: `${this.$t("common.inputInfo")}`,
        //     trigger: "change",
        //   },
        // ],
        feedingStatus: [
          {
            required: true,
            message: `${this.$t("common.selectInfo")}`,
            trigger: "change",
          },
        ],
        // tagSerialNumber: [
        //   {
        //     required: true,
        //     message: `${this.$t("common.selectInfo")}`,
        //     trigger: "change",
        //   },
        // ],
      },
      workOrderList: [
        // {
        //   workCode: "1100005867001",
        // },
      ],
      levels: [
        { label: "特急", value: "2" },
        { label: "紧急", value: "1" },
        { label: "一般", value: "0" },
      ],
      effects: [
        { label: "影响生产", value: "1" },
        { label: "不影响生产", value: "0" },
      ],
      workInfo: {},
      addList: [],
      wareHouseList: {},
      wareHouseList2: [],
    };
  },
  mounted(){
    this.getWareHouse2()
  },
  methods: {
    reset() {
      this.$set(this, "social", []);
      this.$set(this, "addList", []);
    },
    getWareHouse() {
      this.axios({
        url: "/dms/mobileEnd/getUseWarehouse",
        method: "get",
        params: {
          deviceNo: this.workInfo.deviceCode,
        },
      }).then((res) => {
        this.wareHouseList = res.data || {};
      });
    },
    getWareHouse2() {
      this.axios({
        url: "/dms/materialOperation/queryWarehouse",
        method: "get",
      }).then((res) => {
        this.wareHouseList2 = res.data || [];
      });
    },
    handleChange(val) {
      this.axios({
        url: "/dms/mobile/selectWorkByWorkCode",
        method: "get",
        params: {
          workCode: val.value,
        },
      }).then((res) => {
        this.workInfo = res.data || {};
        this.getWareHouse();
        if (this.formTop.shiftTime) {
          this.shiftTimeChange(this.formTop.shiftTime);
        }
      });
    },
    shiftTimeChange(val) {
      this.shiftList = [];
      this.formTop.shiftId = null;
      this.reset();
      if (val) {
        this.formTop.shiftTime = val;
        this.getShiftList(val);
      }
    },
    getShiftList(shiftTime) {
      this.shiftList = [];
      this.formTop.shiftId = null;
      this.formTop.shift = null;
      this.axios({
        url: "/dms/mobile/getShiftList",
        method: "get",
        params: {
          shiftDate: shiftTime ? moment(shiftTime).format("YYYY-MM-DD") : "",
          deviceNo: this.workInfo.deviceCode,
        },
      }).then((res) => {
        this.shiftList = res.data;
        this.formTop.shift = res.data[0].shift;
        this.formTop.shiftId = res.data[0].id;
        this.getAddList();
      });
    },
    shiftChange(obj) {
      this.formTop.shift = obj.label;
      this.formTop.shiftId = obj.value;
      this.getAddList();
    },
    getAddList() {
      if (!this.formTop.workCode && !this.formTop.shiftId) {
        this.$Message.warning("请先选择工单和班次");
        return;
      }
      this.axios({
        url: "/dms/mobileEnd/getMaterialAddList",
        method: "get",
        params: {
          pageSize: 50,
          pageNum: 1,
          workCode: this.formTop.workCode,
          shiftId: this.formTop.shiftId,
        },
      }).then((res) => {
        this.addList = res.data.records.map((item) => {
          return {
            ...item,
            weight: 1,
          };
        });
      });
    },
    show() {
      this.$refs.deviceForm.resetFields();
      this.reset();
      this.workOrderList = [];
      this.deviceVisible = true;
      this.formTop = {
        shiftTime: "", // moment().format('YYYY-MM-DD')
        shiftId: null,
        shift: null,
      };
    },
    submit() {
      this.$refs.deviceForm.validate((valid) => {
        if (valid) {
          if (this.social.length === 0)
            return this.$Message.warning("请选择一条数据");
          let result = true;
          for (let index = 0; index < this.social.length; index++) {
            const element = this.social[index];
            if (!element.weight) {
              result = false;
            }
          }
          if (!result) {
            this.$Message.warning("选择数据的数量不能为空或者是0");
            return;
          }
          const paramList = this.social.map((item) => {
            const warehouse = this.wareHouseList.backupName;
            const warehouseId = this.wareHouseList.id;
            let selectedWarehouse;
            if(item.selectedWarehouseId){
              selectedWarehouse = this.wareHouseList2.find(val=>val.id==item.selectedWarehouseId).backupName;
            }

            return {
              feedingStatus: this.formTop.feedingStatus,
              materialCode: item.materialCode,
              materialBatch: item.materialBatch,
              workCode: this.formTop.workCode,
              shiftId: this.formTop.shiftId,
              shift: this.formTop.shift,
              shiftTime: this.formTop.shiftTime,
              weight: item.weight,
              warehouseId,
              selectedWarehouse,
              selectedWarehouseId:item.selectedWarehouseId,
              warehouse,
              brand: item.brand,
              remarks: item.remarks,
              unit: item.unit,
              tagSerialNumber: item.tagSerialNumber || null,
            };
          });
console.log(paramList);
          const url =
            this.formTop.feedingStatus === "投料"
              ? "/dms/mobileEnd/addMaterialOperation"
              : "/dms/mobileEnd/updateMaterialOperation";
          console.log("url:", url);
          console.log("data:", paramList);
          const checkData = paramList.map((item) => {
            return {
              workCode: item.workCode,
              materialCode: item.materialCode,
              batchNumber: item.materialBatch || "",
            };
          });
          const that=this;
          that.axios({
            url: "/dms/materialOperation/queryMaterialLimitation",
            data: checkData,
            method: "post",
          }).then((res) => {
            if (res.data.includes(1)) return this.$Message.error("禁止挪用投料");
            else {
              that.$refs.commonModal.showModal({
                title: "确认",
                type: "sure",
                desc:res.data.includes(2)?'该投料订单与当前生产订单无关':'确认提交吗',
                submit: () => {
                  that.addAxios(url, paramList);
                },
              });
            }
          });
        }
      });
    },
    addAxios(url, paramList) {
      this.axios({
        url,
        data: paramList,
        method: "post",
      }).then((res) => {
        if (res.code == 200) {
          this.$Message.success("操作成功");
          this.deviceVisible = false;
          this.$emit("refresh");
        } else {
          this.$Message.error(res.msg);
        }
      });
    },
    handleRemote(query) {
      if (query !== "") {
        this.searchLoading = true;
        let _query = query.split("-");
        if (Array.isArray(_query)) _query = _query[0];
        this.axios({
          method: "post",
          url: "/dms/productionWork/queryWorkList",
          data: {
            pageSize: 50,
            pageNum: 1,
            workCode: _query,
          },
        })
          .then((res) => {
            if (res.code === 200) {
              this.workOrderList = res.data.records;
            } else {
              this.$Message.warning({
                content: res.msg,
                duration: 6,
                closable: true,
              });
            }
          })
          .finally(() => {
            this.searchLoading = false;
          });
      } else {
        this.workOrderList = [];
      }
    },
  },
};
</script>

<style lang="scss" scoped>
/deep/ .ivu-modal-body {
  background: transparent !important;
  padding: 0 !important;
  box-shadow: none;
}

.item {
  background: #fff;
  border-radius: 8px;
  padding: 16px;
  box-shadow: 0px 4px 8px 0px rgba(0, 20, 45, 0.04);
}

.demo-upload-list {
  position: relative;
  width: 60px;
  height: 60px;
  text-align: center;
  line-height: 60px;
  border-radius: 4px;
  background: #fff;
  box-shadow: 0 1px 1px rgba(0, 0, 0, 0.2);
  margin-left: 15px;

  img {
    width: 100%;
    height: 100%;
  }

  .delIcon {
    position: absolute;
    right: -10px;
    top: -10px;
    color: red;
    font-size: 20px;
    background: #fff;
    border-radius: 50%;
    cursor: pointer;
  }
}
</style>
